package com.chandra.pos.security;

import com.chandra.pos.employee.dao.entity.Employee;
import com.chandra.pos.employee.dao.entity.EmployeeRole;
import com.chandra.pos.employee.exception.SystemUserNotFoundException;
import com.chandra.pos.employee.service.IEmployeeManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.CannotCreateTransactionException;

import javax.inject.Named;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * UserEntity: chandra shekher kumar
 * Date: 5/31/12
 * Time: 1:26 PM
 * To change this template use File | Settings | File Templates.
 */

@Named("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IEmployeeManager employeeManager;


    @Override

    public org.springframework.security.core.userdetails.UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Employee   employee=null;



        try {
               employee = employeeManager.getUserDetail(username);
        } catch (SystemUserNotFoundException e) {
            throw new UsernameNotFoundException("Could not find: " + username);

        } catch (CannotCreateTransactionException e) {


            throw new UsernameNotFoundException("nt");

        }

        List<EmployeeRole> employeeRoleList= employeeManager.getUserRoles(employee);

        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (EmployeeRole role : employeeRoleList) {
            authorities.add(new SimpleGrantedAuthority(role.getRole().getName()));
        }

      UserDetails user = new UserDetailsImpl(employee, authorities);


        return user;
    }



}
